import os

from django.conf import settings


class WriteFilesClass:
    def __init__(self,obj=None,file_type=None):
        """
        obj: 从前端获取的文件对象
        file_type:文件的类型 （img，music，video）
        file_dir ：本地文件的路径
        """
        self.obj = obj
        self.file_type = file_type
        self.objName = "" #写入的文件路径
        self.file_dir = "" #本地的文件路径

    # 写入文件
    def write_files(self):
        if self.file_type == "img":
            # 拼接图片所在完整路径
            self.objName = os.path.join(settings.IMG_ROOT, self.obj.name)
            print(self.objName)
        elif self.file_type == "music":
            # 拼接图片所在完整路径
            self.objName = os.path.join(settings.MUSIC_ROOT, self.obj.name)
            print(self.objName)
        elif self.file_type == "video":
            # 拼接图片所在完整路径
            self.objName = os.path.join(settings.VIDEO_ROOT, self.obj.name)
            print(self.objName)
        # IO操作，chunks()一点点的读取;
        with open(self.objName, 'wb') as f:
            for i in self.obj.chunks():
                f.write(i)

        # 构建参数
        context = {
            'obj_name': self.objName,
            'url': settings.URL
        }
        return context

    # 读取文件
    def read_files(self):
        file_list = []
        if self.file_type == "img":
            self.file_dir = "static\imgs"
        elif self.file_type == "music":
            self.file_dir = "static\music"
        elif self.file_type == "video":
            self.file_dir = r"static\video"
        # 获取图片所在的路径下的所有图片名称
        for root, dirs, files in os.walk(self.file_dir):
            file_list.append(files)
        # print(f"图片列表：{photo_list}")
        one_list = [i for j in file_list for i in j]
        print(f"图片列表：{one_list}")

        context = {
            'url': settings.URL,
            'one_list': one_list
        }
        return context
